package com.aloda.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.aloda.ai.AiPlatformTypeExecutor;
import com.aloda.annotation.RateLimit;
import com.aloda.cache.RedisUtils;
import com.aloda.constant.*;
import com.aloda.context.UserBaseContext;
import com.aloda.dto.AiGenerateResultDTO;
import com.aloda.dto.AiMessageDTO;
import com.aloda.dto.scoringResult.*;
import com.aloda.dto.user.UserSafetyDTO;
import com.aloda.entity.App;
import com.aloda.entity.Question;
import com.aloda.entity.ScoringResult;
import com.aloda.entity.UserToken;
import com.aloda.enums.AiModelEnums;
import com.aloda.enums.AiPlatformEnum;
import com.aloda.enums.AppTypeEnum;
import com.aloda.enums.ReviewStatusEnum;
import com.aloda.exception.BaseException;
import com.aloda.exception.WarnException;
import com.aloda.mapper.AppMapper;
import com.aloda.mapper.QuestionMapper;
import com.aloda.mapper.ScoringResultMapper;
import com.aloda.mapper.UserTokenMapper;
import com.aloda.query.ScoringResultPageDTO;
import com.aloda.query.ScoringResultUserPageDTO;
import com.aloda.result.PageResult;
import com.aloda.service.ScoringResultService;
import com.aloda.utils.CheckUtils;
import com.aloda.utils.MyJsonUtils;
import com.aloda.utils.TokensTreatUtils;
import com.aloda.vo.scoringResult.ScoringResultExportVO;
import com.aloda.vo.scoringResult.ScoringResultGenerateVO;
import com.aloda.vo.scoringResult.ScoringResultInfoVO;
import com.aloda.vo.scoringResult.ScoringResultPageVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author aloda
 * @description 针对表【scoring_result(评分结果)】的数据库操作Service实现
 * @createDate 2025-03-05 16:27:38
 */
@Slf4j
@Service
public class ScoringResultServiceImpl extends ServiceImpl<ScoringResultMapper, ScoringResult> implements ScoringResultService {

    @Resource
    private ScoringResultMapper scoringResultMapper;

    @Resource
    private AppMapper appMapper;

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private UserTokenMapper userTokenMapper;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private AiPlatformTypeExecutor aiPlatformTypeExecutor;

    /**
     * 分页查询
     *
     * @param scoringResultPageDTO
     * @return
     */
    @Override
    public PageResult<ScoringResultPageVO> pageQuery(ScoringResultPageDTO scoringResultPageDTO) {
        Page<ScoringResult> page = scoringResultPageDTO.toMpPageDefaultSortByUpdateTimeDesc();
        LambdaQueryWrapper<ScoringResult> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(scoringResultPageDTO.getResultName() != null, ScoringResult::getResultName, scoringResultPageDTO.getResultName())
                .like(scoringResultPageDTO.getAppId() != null, ScoringResult::getAppId, scoringResultPageDTO.getAppId())
                .like(scoringResultPageDTO.getCreateUser() != null, ScoringResult::getCreateUser, scoringResultPageDTO.getCreateUser())
                .between(scoringResultPageDTO.getBeginTime() != null && scoringResultPageDTO.getEndTime() != null,
                        ScoringResult::getCreateTime, scoringResultPageDTO.getBeginTime(), scoringResultPageDTO.getEndTime());
        scoringResultMapper.selectPage(page, lambdaQueryWrapper);
        return PageResult.of(page, ScoringResultPageVO.class);
    }

    /**
     * 新增评分结果
     *
     * @param scoringResultAddDTO
     * @return
     */
    @Override
    public long addResult(ScoringResultAddDTO scoringResultAddDTO) {
        // 1.校验参数
        checkAddDTO(scoringResultAddDTO);
        // 4.创建评分结果
        ScoringResult scoringResult = BeanUtil.copyProperties(scoringResultAddDTO, ScoringResult.class);
        App app = appMapper.selectById(scoringResultAddDTO.getAppId());
        if (BeanUtil.isEmpty(app)) {
            throw new BaseException(ExceptionConstant.APP_NOT_EXIST);
        }
        scoringResult.setCreateUser(app.getCreateUser());
        scoringResult.setUserId(app.getUserId());
        scoringResult.setCreateTime(LocalDateTime.now());
        scoringResult.setUpdateTime(LocalDateTime.now());
        // 5.插入数据
        scoringResultMapper.insert(scoringResult);
        // 删除app对应的所有题目选项缓存
        String prefixKey = RedisConstant.APP_USER_ANSWER + app.getId().toString() + ":";
        redisUtils.deleteObjectFormCacheByPrefix(prefixKey);
        return scoringResult.getId();
    }

    /**
     * 编辑评分结果
     *
     * @param scoringResultEditDTO
     */
    @Override
    public void editResult(ScoringResultEditDTO scoringResultEditDTO) {
        // 1.校验参数
        checkEditDTO(scoringResultEditDTO);
        // 4.修改参数
        ScoringResult scoringResult = BeanUtil.copyProperties(scoringResultEditDTO, ScoringResult.class);
        scoringResult.setUpdateTime(LocalDateTime.now());
        // 5.更新
        scoringResultMapper.updateById(scoringResult);
        // 删除app对应的所有题目选项缓存
        String prefixKey = RedisConstant.APP_USER_ANSWER + scoringResultEditDTO.getAppId().toString() + ":";
        redisUtils.deleteObjectFormCacheByPrefix(prefixKey);
    }

    /**
     * 导出评分结果信息表格
     *
     * @param response
     * @param ids
     */
    @Override
    public void exportToExcel(HttpServletResponse response, List<Long> ids) {
        try {
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("评分结果信息表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 查询所有员工信息 如果ids为空查询所有信息，否则查询对应信息
            LambdaQueryWrapper<ScoringResult> queryWrapper = new LambdaQueryWrapper<>();
            List<ScoringResult> list;
            if (ids.isEmpty()) {
                list = scoringResultMapper.selectList(queryWrapper);
            } else {
                list = scoringResultMapper.selectBatchIds(ids);
            }

            // 转换为导出VO
            List<ScoringResultExportVO> exportVOList = list.stream().map(scoringResult -> BeanUtil.copyProperties(scoringResult, ScoringResultExportVO.class))
                    .collect(Collectors.toList());

            // 使用EasyExcel导出
            EasyExcel.write(response.getOutputStream(), ScoringResultExportVO.class)
                    .sheet("评分结果信息")
                    .doWrite(exportVOList);

        } catch (IOException e) {
            throw new RuntimeException(ExceptionConstant.EXPORT_EXCEL_ERROR, e);
        }
    }

    /**
     * 客户端新增评分结果
     *
     * @param scoringResultAddDTO
     * @return
     */
    @Override
    @RateLimit(limit = 2, period = 10)
    public long addResultByUser(ScoringResultAddDTO scoringResultAddDTO) {
        // 1.校验参数
        App app = checkAddDTO(scoringResultAddDTO);
        // 2.检查是否为该应用创建用户
        UserSafetyDTO user = UserBaseContext.getUser();
        if (!app.getUserId().equals(user.getId())) {
            throw new BaseException(ErrorCode.FORBIDDEN_ERROR);
        }
        // 3.新增评分结果
        ScoringResult scoringResult = BeanUtil.copyProperties(scoringResultAddDTO, ScoringResult.class);
        scoringResult.setUserId(user.getId());
        scoringResult.setCreateUser(user.getUserAccount());
        scoringResult.setCreateTime(LocalDateTime.now());
        scoringResult.setUpdateTime(LocalDateTime.now());
        // 4.插入数据
        scoringResultMapper.insert(scoringResult);
        // 更新app状态
        app.setReviewStatus(ReviewStatusEnum.REVIEWING.getValue());
        app.setUpdateTime(LocalDateTime.now());
        appMapper.updateById(app);
        // 删除app对应的所有题目选项缓存
        String prefixKey = RedisConstant.APP_USER_ANSWER + app.getId().toString() + ":";
        redisUtils.deleteObjectFormCacheByPrefix(prefixKey);
        // 5.返回主键id
        return scoringResult.getId();
    }

    /**
     * 客户端分页查询评分结果
     *
     * @param scoringResultUserPageDTO
     * @return
     */
    @Override
    public PageResult<ScoringResultPageVO> pageQueryByUser(ScoringResultUserPageDTO scoringResultUserPageDTO) {
        if (scoringResultUserPageDTO.getPageSize() > UserConstant.USER_MAX_PAGE_SIZE) {
            throw new WarnException(ErrorCode.PARAMS_ERROR);
        }
        Long appId = scoringResultUserPageDTO.getAppId();
        if (appId == null) {
            throw new WarnException(ErrorCode.PARAMS_ERROR);
        }
        App app = appMapper.selectById(appId);
        if (BeanUtil.isEmpty(app)) {
            throw new BaseException(ExceptionConstant.APP_NOT_EXIST);
        }
        if (!app.getUserId().equals(UserBaseContext.getUser().getId())) {
            throw new BaseException(ErrorCode.FORBIDDEN_ERROR);
        }
        Page<ScoringResult> page = scoringResultUserPageDTO.toMpPageDefaultSortByUpdateTimeDesc();
        LambdaQueryWrapper<ScoringResult> scoringResultLambdaQueryWrapper = new LambdaQueryWrapper<>();
        scoringResultLambdaQueryWrapper
                .like(scoringResultUserPageDTO.getResultName() != null, ScoringResult::getResultName,
                        scoringResultUserPageDTO.getResultName())
                .like(scoringResultUserPageDTO.getResultDesc() != null, ScoringResult::getResultDesc,
                        scoringResultUserPageDTO.getResultDesc())
                .eq(ScoringResult::getAppId, appId);
        scoringResultMapper.selectPage(page, scoringResultLambdaQueryWrapper);
        return PageResult.of(page, ScoringResultPageVO.class);
    }

    /**
     * 客户端编辑评分结果
     *
     * @param scoringResultEditDTO
     * @return
     */
    @Override
    public long editResultByUser(ScoringResultEditDTO scoringResultEditDTO) {
        // 1.校验参数
        App app = checkEditDTO(scoringResultEditDTO);
        // 2.校验是否为app创建者
        UserSafetyDTO user = UserBaseContext.getUser();
        if (!app.getUserId().equals(user.getId())) {
            throw new BaseException(ErrorCode.FORBIDDEN_ERROR);
        }
        // 3.校验是否为评分结果创建者
        Long id = scoringResultEditDTO.getId();
        ScoringResult scoringResult = scoringResultMapper.selectById(id);
        if (BeanUtil.isEmpty(scoringResult)) {
            throw new BaseException(ExceptionConstant.RESULT_NOT_EXIST);
        }
        if (!scoringResult.getUserId().equals(user.getId())) {
            throw new BaseException(ErrorCode.FORBIDDEN_ERROR);
        }
        // 4.更新参数
        BeanUtil.copyProperties(scoringResultEditDTO, scoringResult);
        scoringResult.setUpdateTime(LocalDateTime.now());
        scoringResultMapper.updateById(scoringResult);
        // 更新app状态
        app.setReviewStatus(ReviewStatusEnum.REVIEWING.getValue());
        app.setUpdateTime(LocalDateTime.now());
        appMapper.updateById(app);
        // 删除app对应的所有题目选项缓存
        String prefixKey = RedisConstant.APP_USER_ANSWER + app.getId().toString() + ":";
        redisUtils.deleteObjectFormCacheByPrefix(prefixKey);
        return scoringResult.getId();
    }

    /**
     * 客户端获取评分结果详情
     *
     * @param id
     * @return
     */
    @Override
    public ScoringResultInfoVO getResultById(Long id) {
        if (id == null) {
            throw new WarnException(ErrorCode.PARAMS_ERROR);
        }
        ScoringResult scoringResult = scoringResultMapper.selectById(id);
        if (BeanUtil.isEmpty(scoringResult)) {
            throw new BaseException(ExceptionConstant.RESULT_NOT_EXIST);
        }
        UserSafetyDTO user = UserBaseContext.getUser();
        if (!scoringResult.getUserId().equals(user.getId())) {
            throw new BaseException(ErrorCode.FORBIDDEN_ERROR);
        }
        return BeanUtil.copyProperties(scoringResult, ScoringResultInfoVO.class);
    }

    /**
     * 客户端删除评分结果
     *
     * @param ids
     * @return
     */
    @Override
    public long deleteResultByIds(List<Long> ids) {
        // 1.如果ids为空返回参数错误
        if (ids.isEmpty()) {
            throw new WarnException(ErrorCode.PARAMS_ERROR);
        }
        // 2.如果对应的结果列表中有不是该用户创建的结果返回禁止访问
        UserSafetyDTO user = UserBaseContext.getUser();
        List<ScoringResult> list = scoringResultMapper.selectBatchIds(ids);
        if (list.isEmpty()) {
            throw new BaseException(ExceptionConstant.RESULT_NOT_EXIST);
        }
        list.forEach(scoringResult -> {
            if (!scoringResult.getUserId().equals(user.getId())) {
                throw new BaseException(ErrorCode.FORBIDDEN_ERROR);
            }
        });
        // 3.删除
        int i = scoringResultMapper.deleteByIds(ids);
        // 删除所有app对应的所有题目选项缓存
        Set<Long> appIds = list.stream().map(ScoringResult::getAppId).collect(Collectors.toSet());
        for (Long appId : appIds) {
            String prefixKey = RedisConstant.APP_USER_ANSWER + appId.toString() + ":";
            redisUtils.deleteObjectFormCacheByPrefix(prefixKey);
        }
        return i;
    }

    /**
     * AI生成评分结果
     *
     * @param scoringResultGenerateDTO
     * @return
     */
    @Override
    public List<ScoringResultGenerateVO> aiGenerate(ScoringResultGenerateDTO scoringResultGenerateDTO) {
        // 1.校验参数
        if (scoringResultGenerateDTO.getResultNum() > AppConstant.APP_GENERATE_RESULT_MAX_NUM) {
            throw new BaseException(ExceptionConstant.SCORING_RESULT_OUT_MAX);
        }
        // 2.检查应用是否存在
        Long appId = scoringResultGenerateDTO.getAppId();
        if (appId == null) {
            throw new WarnException(ErrorCode.PARAMS_ERROR);
        }
        App app = appMapper.selectById(appId);
        if (BeanUtil.isEmpty(app)) {
            throw new BaseException(ExceptionConstant.APP_NOT_EXIST);
        }
        // 3.找出应用对应题目
        LambdaQueryWrapper<Question> questionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        questionLambdaQueryWrapper.eq(Question::getAppId, appId);
        Question question = questionMapper.selectOne(questionLambdaQueryWrapper);
        if (BeanUtil.isEmpty(question) || question.getQuestionContent().isEmpty()) {
            throw new BaseException(ExceptionConstant.QUESTION_NOT_EXIST);
        }

        Long userId = UserBaseContext.getUser().getId();
        String key = "user:" + userId.toString() + ":result-gen-lock";
        RLock lock = redissonClient.getLock(key);
        try {
            if (lock.tryLock(10, 60, TimeUnit.SECONDS)) {

                // 2.1.检查该用户是否有token余量
                LambdaQueryWrapper<UserToken> userTokenLambdaQueryWrapper = new LambdaQueryWrapper<>();
                userTokenLambdaQueryWrapper.eq(UserToken::getUserId, userId);
                UserToken userToken = userTokenMapper.selectOne(userTokenLambdaQueryWrapper);
                if (BeanUtil.isEmpty(userToken) || userToken.getTokenNum() <= 0) {
                    throw new BaseException(ExceptionConstant.USER_TOKEN_NOT_ENOUGH);
                }
                // 3.1.计算余量token是否满足这次使用
                Long needTokens = TokensTreatUtils.calculateTokensGenerateResult(question.getQuestionContent(), scoringResultGenerateDTO.getResultNum());
                log.info("用户{}调用AI预计tokens:{}", userId, needTokens);
                if (needTokens > userToken.getTokenNum()) {
                    throw new BaseException(ExceptionConstant.USER_TOKEN_NOT_ENOUGH);
                }
                // 4.封装用户消息
                String userMessage = getGenerateResultUserMessage(app, question.getQuestionContent(), scoringResultGenerateDTO.getResultNum());
                // 5.AI生成评分结果
                // 获取AI消息数据传输对象
                AiMessageDTO aiMessageDTO = new AiMessageDTO();
                aiMessageDTO.setSystemMessage(AiConstant.GENERATE_RESULT_SYSTEM_MESSAGE);
                aiMessageDTO.setUserMessage(userMessage);
                aiMessageDTO.setTemperature(AiConstant.DEFAULT_TEMPERATURE);
                AiPlatformEnum enumByValue = AiPlatformEnum.getEnumByValue(scoringResultGenerateDTO.getPlatform());
                if (enumByValue == null) {
                    throw new BaseException(ExceptionConstant.PLATFORM_NOT_EXIST);
                }
                aiMessageDTO.setAiPlatform(enumByValue);
                AiModelEnums aiModel = AiModelEnums.getEnumByValue(scoringResultGenerateDTO.getModel());
                if (aiModel == null) {
                    throw new BaseException(ExceptionConstant.MODEL_NOT_EXIST);
                }
                aiMessageDTO.setModel(aiModel.getValue());

                AiGenerateResultDTO aiGenerateResultDTO = null;
                try {
                    aiGenerateResultDTO = aiPlatformTypeExecutor.doSyncRequest(aiMessageDTO);
                    log.info("用户{}调用AI结果:{}",userId, aiGenerateResultDTO);
                } catch (Exception e) {
                    log.info("调用AI失败", e);
                    throw new BaseException(e.getMessage());
                }

                // 6. 解析JSON
                List<ScoringResultAiDTO> resultAiDTOList;
                try {
                    // 处理生成结果
                    String cleanedJson = MyJsonUtils.cleanJsonString(aiGenerateResultDTO.getResult());
                    resultAiDTOList = JSONUtil.toList(cleanedJson, ScoringResultAiDTO.class);
                } catch (Exception e) {
                    throw new BaseException(ExceptionConstant.AI_GENERATE_ERROR);
                }
                // 7.通过返回结果扣除token,如果小于0,直接计为0
                userToken.setTokenNum(userToken.getTokenNum() - aiGenerateResultDTO.getTokenNum());
                if (userToken.getTokenNum() < 0) {
                    userToken.setTokenNum(0L);
                }
                userTokenMapper.updateById(userToken);
                // 8.封装返回结果
                return resultAiDTOList.stream().map(scoringResultAiDTO -> {
                    ScoringResultGenerateVO scoringResultGenerateVO = BeanUtil.copyProperties(scoringResultAiDTO, ScoringResultGenerateVO.class);
                    scoringResultGenerateVO.setAppId(appId);
                    return scoringResultGenerateVO;
                }).toList();
            } else {
                throw new BaseException(ExceptionConstant.SYSTEM_BUSY);
            }
        }catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new BaseException(ErrorCode.SYSTEM_ERROR);
        } finally {
            if (lock != null && lock.isLocked()) {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
    }

    /**
     * 批量新增评分结果
     *
     * @param batchSResultAddDTO
     * @return
     */
    @Override
    @RateLimit(limit = 2, period = 10)
    public void saveGenerateResultBatch(BatchSResultAddDTO batchSResultAddDTO) {
        // 1.校验参数
        Long appId = batchSResultAddDTO.getAppId();
        if (appId == null) {
            throw new WarnException(ErrorCode.PARAMS_ERROR);
        }
        App app = appMapper.selectById(appId);
        if (BeanUtil.isEmpty(app)) {
            throw new BaseException(ExceptionConstant.APP_NOT_EXIST);
        }
        // todo: 需要考虑用户是否篡改了数据
        // 2.处理数据
        UserSafetyDTO user = UserBaseContext.getUser();
        List<ScoringResultAiDTO> list = batchSResultAddDTO.getList();
        List<ScoringResult> scoringResults = list.stream().map(scoringResultAiDTO -> {
            ScoringResult scoringResult = new ScoringResult();
            BeanUtil.copyProperties(scoringResultAiDTO, scoringResult);
            scoringResult.setAppId(appId);
            scoringResult.setUserId(user.getId());
            scoringResult.setCreateUser(user.getUserAccount());
            scoringResult.setCreateTime(LocalDateTime.now());
            scoringResult.setUpdateTime(LocalDateTime.now());
            return scoringResult;
        }).toList();
        // 3.保存数据
        scoringResultMapper.insert(scoringResults);
        // 更新app状态
        app.setReviewStatus(ReviewStatusEnum.REVIEWING.getValue());
        app.setUpdateTime(LocalDateTime.now());
        appMapper.updateById(app);
        // 删除app对应的所有题目选项缓存
        String prefixKey = RedisConstant.APP_USER_ANSWER + app.getId().toString() + ":";
        redisUtils.deleteObjectFormCacheByPrefix(prefixKey);
    }

    private App checkAddDTO(ScoringResultAddDTO scoringResultAddDTO) {
        // 1.校验参数
        if (!CheckUtils.checkResultName(scoringResultAddDTO.getResultName())) {
            throw new BaseException(ExceptionConstant.FORMAT_ERROR);
        }
        if (!CheckUtils.checkResultDesc(scoringResultAddDTO.getResultDesc())) {
            throw new BaseException(ExceptionConstant.FORMAT_ERROR);
        }
        if (!CheckUtils.checkResultProp(scoringResultAddDTO.getResultProp())) {
            throw new BaseException(ExceptionConstant.FORMAT_ERROR);
        }
        if (!CheckUtils.checkResultScoreRange(scoringResultAddDTO.getResultScoreRange())) {
            throw new BaseException(ExceptionConstant.FORMAT_ERROR);
        }
        // 2.校验app是否存在
        App app = appMapper.selectById(scoringResultAddDTO.getAppId());
        if (BeanUtil.isEmpty(app)) {
            throw new BaseException(ExceptionConstant.APP_NOT_EXIST);
        }
        // 3.app存在校验评分范围是否已存在
        LambdaQueryWrapper<ScoringResult> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(scoringResultAddDTO.getResultScoreRange() != null,
                        ScoringResult::getResultScoreRange,
                        scoringResultAddDTO.getResultScoreRange())
                .eq(scoringResultAddDTO.getAppId() != null,
                        ScoringResult::getAppId,
                        scoringResultAddDTO.getAppId());
        Long count = scoringResultMapper.selectCount(lambdaQueryWrapper);
        if (count > 0) {
            throw new BaseException(ExceptionConstant.RANGE_IS_EXIST);
        }
        return app;
    }

    private App checkEditDTO(ScoringResultEditDTO scoringResultEditDTO) {
        if (!CheckUtils.checkResultName(scoringResultEditDTO.getResultName())) {
            throw new BaseException(ExceptionConstant.FORMAT_ERROR);
        }
        if (!CheckUtils.checkResultDesc(scoringResultEditDTO.getResultDesc())) {
            throw new BaseException(ExceptionConstant.FORMAT_ERROR);
        }
        if (!CheckUtils.checkResultProp(scoringResultEditDTO.getResultProp())) {
            throw new BaseException(ExceptionConstant.FORMAT_ERROR);
        }
        if (!CheckUtils.checkResultScoreRange(scoringResultEditDTO.getResultScoreRange())) {
            throw new BaseException(ExceptionConstant.FORMAT_ERROR);
        }
        // 2.校验app是否存在
        App app = appMapper.selectById(scoringResultEditDTO.getAppId());
        if (BeanUtil.isEmpty(app)) {
            throw new BaseException(ExceptionConstant.APP_NOT_EXIST);
        }
        // 3.app存在校验评分范围是否已存在
        LambdaQueryWrapper<ScoringResult> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(scoringResultEditDTO.getResultScoreRange() != null,
                        ScoringResult::getResultScoreRange,
                        scoringResultEditDTO.getResultScoreRange())
                .eq(scoringResultEditDTO.getAppId() != null,
                        ScoringResult::getAppId,
                        scoringResultEditDTO.getAppId());
        ScoringResult scoringResult = scoringResultMapper.selectOne(lambdaQueryWrapper);
        if (BeanUtil.isNotEmpty(scoringResult) && !scoringResult.getId().equals(scoringResultEditDTO.getId())) {
            throw new BaseException(ExceptionConstant.RANGE_IS_EXIST);
        }
        return app;
    }

    /**
     * 生成结果的用户消息
     * @param app
     * @param questionContent
     * @param resultNum
     * @return
     */
    private String getGenerateResultUserMessage(App app, String questionContent ,int resultNum) {
        StringBuilder userMessage = new StringBuilder();
        userMessage.append(app.getAppName()).append("\n");
        userMessage.append(AppTypeEnum.getEnumByValue(app.getAppType()).getText() + "类").append("\n");
        userMessage.append(questionContent).append("\n");
        userMessage.append(resultNum);
        return userMessage.toString();
    }
}




